package org.zfes.snowier.cloud.zbss.loan.wx.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.zfes.snowier.auth.biz.dao.AuthUserMapper;
import org.zfes.snowier.auth.biz.model.AuthUser;
import org.zfes.snowier.auth.shiro.consts.AuthConsts;
import org.zfes.snowier.auth.shiro.suser.SessionUser;
import org.zfes.snowier.auth.shiro.suser.SessionUserManager;
import org.zfes.snowier.cloud.zbss.loan.config.dic.service.IDicSysconfigService;
import org.zfes.snowier.cloud.zbss.loan.util.CloudStockConst;
import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.web.annos.RepeatToken;
import org.zfes.snowier.web.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Optional;

@Controller("weiChatAuthController")
@RequestMapping("/loan/weichatAuth")
public class WeiChatAuthController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SessionUserManager sessionUserManager;

    @Autowired
    private RestTemplate restTemplate;

	@Autowired
	private AuthUserMapper authUserMapper;

	@Autowired
    private IDicSysconfigService dicSysconfigService;

    @RequestMapping(value = "/callBack", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object weixinAauth2AuthorizeCallBack(HttpServletRequest request, HttpServletResponse response, String code) throws IOException {
        logger.debug("code:||" + code);
        logger.debug("QueryString:||" + request.getQueryString());
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + getWeiChatAppid() + "&secret=" + getWeiChatSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        //String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + getWeiChatAppid() + "&secret=" + getWeiChatSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        logger.debug("url:||" + url);
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, new LinkedHashMap<>());
        logger.debug("result:||" + result);
        JSONObject responsResult = new JSONObject();
        
        if (ZStrUtil.hasText(result.getString("errcode"))) {
            responsResult.put(CloudStockConst.WebControllerResult.CODE,CloudStockConst.WebControllerCode.STATUS_CODE_201);
            responsResult.put(CloudStockConst.WebControllerResult.ERROR,result.getString("errmsg"));
            ZAlert.serviceLogicalError(result.getString("errmsg"));
            return responsResult;
        }
        String access_token = result.getString("access_token");
        String openid = result.getString("openid");
        logger.debug("access_token:||" + access_token);
        logger.debug("openid:||" + openid);

//        String url2="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
//         JSONObject result2=restTemplate.getForObject(url2, JSONObject.class, new LinkedHashMap<>());
//         if(ZStrUtil.hasText(result2.getString("errcode"))) {//
//        	 ZAlert.serviceLogicalError(result2.getString("errmsg"));
//         }
//         logger.debug("result:||"+result2);
        //Optional<Member> memberOp = memberService.loadMemberByWeiChatOpenId(openid);
        Optional<SessionUser> sessionUserOp = getSessionUserManager().loadSessionUserByAccount(openid);
        SessionUser sessionUser = sessionUserOp.orElse(new SessionUser());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String successRedirectUrl = "/";//index.html";
        String failRedirectUrl = "/index.html";
        if (sessionUserOp.isPresent()) {
            logger.debug("已经注册");
            try {
                //subject.login(new WeiChatAuthToken(sessionUserOp.get().getUsername(), "anonymous".toCharArray()));
            } catch (AuthenticationException e) {
                logger.error(e.getMessage());
                response.sendRedirect(failRedirectUrl + "?rr=3");
            }
            AuthUser roleId = authUserMapper.selectBythirdOpenId(openid);
            sessionUser.setOpenId(openid);
            sessionUser.setRoleId(roleId.getDefaultRole());
            responsResult.put("sessionId",session.getId());
            responsResult.put("menu","");
            session.setAttribute(AuthConsts.SESSION.SESSION_USER_KEY, sessionUser);
            session.setAttribute(AuthConsts.SESSION.SESSION_LOGINORGIN_KEY, "WEICHAT");
            responsResult.put(CloudStockConst.WebControllerResult.CODE,CloudStockConst.WebControllerCode.STATUS_CODE_200);
            responsResult.put(CloudStockConst.WebControllerResult.DATA,sessionUser);
            response.sendRedirect(successRedirectUrl);
        } else {
            logger.debug("没有注册");
            try {
                //subject.login(new WeiChatAuthToken("anonymous", "anonymous".toCharArray()));
            } catch (AuthenticationException e) {
                logger.error(e.getMessage());
                response.sendRedirect(failRedirectUrl + "?rr=2");
            }
            sessionUser.setAuthLevel(0);
            sessionUser.setOpenId(openid);
            sessionUser.setUsername("anonymous");

            session.setAttribute(AuthConsts.SESSION.SESSION_USER_KEY, sessionUser);
            session.setAttribute(AuthConsts.SESSION.SESSION_LOGINORGIN_KEY, "WEICHAT");

            //responsResult.put(CloudStockConst.WebControllerResult.CODE,CloudStockConst.WebControllerCode.STATUS_CODE_202);
            //responsResult.put(CloudStockConst.WebControllerResult.ERROR,"没有注册绑定");
            //responsResult.put(CloudStockConst.WebControllerResult.DATA,sessionUser);
            //response.sendRedirect(successRedirectUrl + "#/register");

        }
        return responsResult;
    }

    public SessionUserManager getSessionUserManager() {
        if (sessionUserManager == null) {
            //sessionUserManager = AppCtxUtil.getAppKey("sessionUserManagerImpl");
        }
        return sessionUserManager;
    }

    public String getWeiChatAppid() {
        return dicSysconfigService.doGetWxAppId().get();
    }

    public String getWeiChatSecret() {
        return dicSysconfigService.doGetWxAppSecret().get();
    }

    @RepeatToken
    @RequestMapping(value = "/getUserInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object weixinCallBack(String code)throws ClientProtocolException, IOException {
        if (!"".equals(code) && code != null) {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb23c2631ae4a16ed&secret=2d51d2320e7ea26a71a50322f78be87d&code=" + code + "&grant_type=authorization_code";
            //logger.debug("url:||" + url);
            //JSONObject result = restTemplate.getForObject(url, JSONObject.class, new LinkedHashMap<>());
            //获取openid和access_token的连接
            String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb23c2631ae4a16ed&secret=2d51d2320e7ea26a71a50322f78be87d&code=" + code + "&grant_type=authorization_code";
            //获取返回的code
            String requestUrl = url.replace("CODE", code);
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //向微信发送请求并获取response
            String response = httpClient.execute(httpGet, responseHandler);
            System.out.println("=========================获取token===================");
            System.out.println(response);
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = (JsonObject) parser.parse(response);
            String access_token = jsonObject.get("access_token").getAsString();
            String openId = jsonObject.get("openid").getAsString();
            System.out.println("=======================用户access_token==============");
            System.out.println(access_token);
            System.out.println(openId);
            //获取用户基本信息的连接
            String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
            String userInfoUrl = getUserInfo.replace("ACCESS_TOKEN", access_token).replace("OPENID", openId);
            HttpGet httpGetUserInfo = new HttpGet(userInfoUrl);
            String userInfo = httpClient.execute(httpGetUserInfo, responseHandler);
            //微信那边采用的编码方式为ISO8859-1所以需要转化
            String json = new String(userInfo.getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("====================userInfo==============================");
            JSONObject jsonResult = JSONObject.parseObject(json);
            if(!jsonResult.isEmpty()){
                return jsonResult;
            }
        }
        return Collections.EMPTY_MAP;
    }
}